package com.powerhua.privilege.web;

import com.powerhua.core.bean.BeansRegisterLocator;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.powerhua.privilege.web.action.ActionInterface;

public class PrivilegeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1338707331469662625L;

	/**
	 * 
	 */ 
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * 
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String servlet = req.getParameter("s");
		String returnType = req.getParameter("t");
		
		// action
		ActionInterface action = (ActionInterface)BeansRegisterLocator.getBean(servlet);
		
		// action result
		String result = action.doAction(req);

		if("redirect".equals(returnType)) {
			RequestDispatcher requestDispacher = req.getRequestDispatcher(result);
			requestDispacher.forward(req, res);
			return;
		} else {
			res.setCharacterEncoding("UTF-8");
			PrintWriter out = res.getWriter();
			out.print(result);
		}
	}

	/**
	 * 
	 */
	public String getServletInfo() {
		return "Action servlet information.";
	}

}
